package cn.maidouya.hrm.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录认证成功成功回调实现AuthenticationSuccessHandler
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    // 重写onAuthenticationSuccess方法
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Map map = new HashMap<>();
        map.put("success",true);
        map.put("message",name+"登录成功");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().print(JSON.toJSONString(map));
        // flush字符流
        response.getWriter().flush();
        response.getWriter().close();
    }
}
